#!/usr/bin/env python
# encoding:utf8
import json
import datetime

location = 'home'
DS18B20  = '28-00000384d1c3'

device   = "/sys/bus/w1/devices/%s/w1_slave" % DS18B20

def ReadTemperature():
    t = 0.0
    h = 0.0
    flag = False
    try:
        f = open(device)
        text = f.read()
        f.close()
        firstline = text.split("\n")[0]
        strCRC = firstline.split(" ")[-1]
        if strCRC == 'YES':
            secondline = text.split("\n")[1]
            temperaturedata = secondline.split(" ")[-1]
            t = float(temperaturedata[2:]) / 1000
        else:
            return json.dumps({'error':{'code':1001, 'msg':'Data crc error.'}})
    except Exception, e:
        return json.dumps({'error':{'code':1002, 'msg':'Cant open deviece %s' % device}})
    time = datetime.datetime.now().isoformat()
    return json.dumps({'temperature' : t, 'humidity' : h,'location': location, 'time' : time})

def main():
    print ReadTemperature()

if __name__ == '__main__':
    main()
